/**
 * Created with CLion.
 * Description: 
 * User: loong
 * Date: 2025/5/19
 * Time: 22:36
 */

#include "SpriteAnim.h"
SpriteAnim * SpriteAnim::AddSpriteAnimChild(ObjectScreen * _parent, const std::string & _file_path, float _scale, Anchor _anchor)
{
    auto sprite_ani = new SpriteAnim();
    sprite_ani->Init();
    sprite_ani->SetAnchor(_anchor);
    sprite_ani->SetTexture(Texture(_file_path));
    sprite_ani->SetScale(_scale);
    sprite_ani->SetParent(_parent);
    _parent->AddChild(sprite_ani);

    return sprite_ani;
}

void SpriteAnim::Update(float _dt)
{
    if(is_finish_)
        return;

    frame_timer_ += _dt;
    if(frame_timer_ >= 1.0f / fps_) {
        ++current_frame_;
        if(current_frame_ >= total_frames_) {
            current_frame_ = 0;
            if(!is_loop_)
                is_finish_ = true;
        }
        frame_timer_   = 0.0f;
    }
    texture_.src_rect.x = texture_.src_rect.w * current_frame_;

    Sprite::Update(_dt);
}

void SpriteAnim::SetTexture(const Texture & texture)
{
    texture_            = texture;
    total_frames_       = texture.src_rect.w / texture.src_rect.h;
    texture_.src_rect.w = texture.src_rect.h;
    size_               = glm::vec2(texture_.src_rect.w, texture_.src_rect.h);
}